home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / glibc108.zip / glibc108 / manual / examples / longopt.c < prev    next >
C/C++ Source or Header  |  1994-02-16  |  2KB  |  93 lines

  1. #include <stdio.h>
  2.  
  3. /* Flag set by @samp{--verbose}.  */
  4. static int verbose_flag;
  5.  
  6. int
  7. main (argc, argv)
  8.      int argc;
  9.      char **argv;
  10. {
  11.   int c;
  12.  
  13.   while (1)
  14.     {
  15.       static struct option long_options[] =
  16.     {
  17.       /* These options set a flag.  */
  18.       {"verbose", 0, &verbose_flag, 1},
  19.       {"brief", 0, &verbose_flag, 0},
  20.       /* These options don't set a flag.
  21.          We distinguish them by their indices.  */
  22.       {"add", 1, 0, 0},
  23.       {"append", 0, 0, 0},
  24.       {"delete", 1, 0, 0},
  25.       {"create", 0, 0, 0},
  26.       {"file", 1, 0, 0},
  27.       {0, 0, 0, 0}
  28.     };
  29.       /* @code{getopt_long} stores the option index here.  */
  30.       int option_index = 0;
  31.  
  32.       c = getopt_long (argc, argv, "abc:d:",
  33.                long_options, &option_index);
  34.  
  35.       /* Detect the end of the options.  */
  36.       if (c == -1)
  37.     break;
  38.  
  39.       switch (c)
  40.     {
  41.     case 0:
  42.       /* If this option set a flag, do nothing else now.  */
  43.       if (long_options[option_index].flag != 0)
  44.         break;
  45.       printf ("option %s", long_options[option_index].name);
  46.       if (optarg)
  47.         printf (" with arg %s", optarg);
  48.       printf ("\n");
  49.       break;
  50.  
  51.     case 'a':
  52.       puts ("option -a\n");
  53.       break;
  54.  
  55.     case 'b':
  56.       puts ("option -b\n");
  57.       break;
  58.  
  59.     case 'c':
  60.       printf ("option -c with value `%s'\n", optarg);
  61.       break;
  62.  
  63.     case 'd':
  64.       printf ("option -d with value `%s'\n", optarg);
  65.       break;
  66.  
  67.     case '?':
  68.       /* @code{getopt_long} already printed an error message.  */
  69.       break;
  70.  
  71.     default:
  72.       abort ();
  73.     }
  74.     }
  75.  
  76.   /* Instead of reporting @samp{--verbose}
  77.      and @samp{--brief} as they are encountered,
  78.      we report the final status resulting from them.  */
  79.   if (verbose_flag)
  80.     puts ("verbose flag is set");
  81.  
  82.   /* Print any remaining command line arguments (not options).  */
  83.   if (optind < argc)
  84.     {
  85.       printf ("non-option ARGV-elements: ");
  86.       while (optind < argc)
  87.     printf ("%s ", argv[optind++]);
  88.       putchar ('\n');
  89.     }
  90.  
  91.   exit (0);
  92. }
  93.